# AI命令安装脚本 - Windows版本

param(
    [switch]$Force,
    [string]$InstallPath = "."
)

# 颜色输出函数
function Write-ColorOutput {
    param(
        [string]$Message,
        [string]$Color = "White"
    )

    switch ($Color) {
        "Red" { Write-Host $Message -ForegroundColor Red }
        "Green" { Write-Host $Message -ForegroundColor Green }
        "Yellow" { Write-Host $Message -ForegroundColor Yellow }
        "Cyan" { Write-Host $Message -ForegroundColor Cyan }
        default { Write-Host $Message }
    }
}

function Write-Info {
    param([string]$Message)
    Write-ColorOutput "[INFO] $Message" "Green"
}

function Write-Warn {
    param([string]$Message)
    Write-ColorOutput "[WARN] $Message" "Yellow"
}

function Write-Error {
    param([string]$Message)
    Write-ColorOutput "[ERROR] $Message" "Red"
}

# 检查Python环境
function Test-PythonEnvironment {
    Write-Info "检查Python环境..."

    try {
        $pythonVersion = python --version 2>&1
        if ($LASTEXITCODE -eq 0) {
            Write-Info "Python版本: $pythonVersion"
            $global:PythonCmd = "python"
            return $true
        }
    } catch {
        Write-Warn "python命令不可用，尝试py命令..."
    }

    try {
        $pyVersion = py --version 2>&1
        if ($LASTEXITCODE -eq 0) {
            Write-Info "Python版本: $pyVersion"
            $global:PythonCmd = "py"
            return $true
        }
    } catch {
        Write-Error "未找到Python环境，请先安装Python 3.7+"
        return $false
    }

    Write-Error "未找到Python环境，请先安装Python 3.7+"
    return $false
}

# 检查依赖
function Test-Dependencies {
    Write-Info "检查系统依赖..."

    # 检查Git
    try {
        $gitVersion = git --version 2>&1
        if ($LASTEXITCODE -eq 0) {
            Write-Info "Git版本: $gitVersion"
        } else {
            Write-Error "未找到Git，请先安装Git"
            return $false
        }
    } catch {
        Write-Error "未找到Git，请先安装Git"
        return $false
    }

    # 检查curl（可选）
    try {
        $curlVersion = curl --version 2>&1 | Select-Object -First 1
        if ($LASTEXITCODE -eq 0) {
            Write-Info "Curl版本: $curlVersion"
        } else {
            Write-Warn "未找到curl，将使用Python的urllib进行下载"
        }
    } catch {
        Write-Warn "未找到curl，将使用Python的urllib进行下载"
    }

    return $true
}

# 创建必要的目录
function New-RequiredDirectories {
    Write-Info "创建必要的目录..."

    $directories = @(
        ".ai\commands",
        ".ai\scripts",
        ".ai\prompts\basic",
        ".ai\prompts\professional",
        ".ai\prompts\creative",
        ".ai\prompts\workflow",
        ".ai\docs",
        "logs",
        "temp"
    )

    foreach ($dir in $directories) {
        $fullPath = Join-Path $InstallPath $dir
        if (-not (Test-Path $fullPath)) {
            New-Item -ItemType Directory -Path $fullPath -Force | Out-Null
            Write-Info "创建目录: $fullPath"
        }
    }
}

# 安装AI命令
function Install-AICommands {
    Write-Info "安装AI命令..."

    $installerPath = Join-Path $InstallPath "ai-code-ext.py"
    if (-not (Test-Path $installerPath)) {
        Write-Error "未找到ai-code-ext.py文件: $installerPath"
        return $false
    }

    try {
        $pythonCmd = if ($global:PythonCmd) { $global:PythonCmd } else { "python" }

        if ($Force) {
            & $pythonCmd $installerPath install --force
        } else {
            & $pythonCmd $installerPath install
        }

        if ($LASTEXITCODE -eq 0) {
            Write-Info "AI命令安装成功"
            return $true
        } else {
            Write-Error "AI命令安装失败"
            return $false
        }
    } catch {
        Write-Error "安装过程中发生异常: $($_.Exception.Message)"
        return $false
    }
}

# 设置权限
function Set-FilePermissions {
    Write-Info "设置文件权限..."

    try {
        # Windows不需要设置执行权限，但可以设置文件属性
        $aiPath = Join-Path $InstallPath ".ai"
        if (Test-Path $aiPath) {
            # 设置文件为只读（可选）
            # Get-ChildItem -Path $aiPath -Recurse -File | Set-ItemProperty -Name IsReadOnly -Value $false
            Write-Info "文件权限设置完成"
        }
    } catch {
        Write-Warn "设置文件权限时出现警告: $($_.Exception.Message)"
    }
}

# 创建配置文件
function New-ConfigurationFile {
    Write-Info "创建配置文件..."

    $configPath = Join-Path $InstallPath ".ai\config.json"
    if (-not (Test-Path $configPath)) {
        try {
            $configContent = @{
                version = "1.0.0"
                installed_at = (Get-Date).ToString("yyyy-MM-ddTHH:mm:ssZ")
                auto_update = $true
                log_level = "info"
                cache_enabled = $true
                prompts_enabled = $true
                default_language = "zh-CN"
            } | ConvertTo-Json -Depth 10

            Set-Content -Path $configPath -Value $configContent -Encoding UTF8
            Write-Info "创建配置文件: $configPath"
        } catch {
            Write-Warn "创建配置文件失败: $($_.Exception.Message)"
        }
    } else {
        Write-Info "配置文件已存在: $configPath"
    }
}

# 验证安装
function Test-Installation {
    Write-Info "验证安装..."

    $errors = 0

    # 检查必要目录
    $requiredDirs = @(".ai\commands", ".ai\prompts", ".ai\scripts", ".ai\docs")
    foreach ($dir in $requiredDirs) {
        $fullPath = Join-Path $InstallPath $dir
        if (-not (Test-Path $fullPath)) {
            Write-Error "缺少目录: $fullPath"
            $errors++
        } else {
            $fileCount = (Get-ChildItem -Path $fullPath -Recurse -File).Count
            Write-Info "$dir 目录: $fileCount 个文件"
        }
    }

    # 检查核心文件
    $requiredFiles = @(
        ".ai\commands\analyze.md",
        ".ai\commands\plan.md",
        ".ai\commands\specify.md",
        ".ai\prompts\README.md",
        ".ai\scripts\install.ps1"
    )

    foreach ($file in $requiredFiles) {
        $fullPath = Join-Path $InstallPath $file
        if (-not (Test-Path $fullPath)) {
            Write-Error "缺少文件: $fullPath"
            $errors++
        } else {
            Write-Info "找到文件: $fullPath"
        }
    }

    if ($errors -eq 0) {
        Write-Info "安装验证通过"
        return $true
    } else {
        Write-Error "安装验证失败，发现 $errors 个问题"
        return $false
    }
}

# 显示使用说明
function Show-Usage {
    Write-Info "安装完成！使用说明："
    Write-Host ""
    Write-Host "1. 查看已安装目录：" -ForegroundColor Cyan
    Write-Host "   python ai-code-ext.py list" -ForegroundColor Yellow
    Write-Host ""
    Write-Host "2. 使用AI命令：" -ForegroundColor Cyan
    Write-Host "   # 从.ai\commands目录选择合适的命令文件" -ForegroundColor Yellow
    Write-Host "   # 复制内容到AI工具中使用" -ForegroundColor Yellow
    Write-Host ""
    Write-Host "3. 使用提示词库：" -ForegroundColor Cyan
    Write-Host "   # 从.ai\prompts目录选择合适的提示词" -ForegroundColor Yellow
    Write-Host "   # 根据需要进行个性化调整" -ForegroundColor Yellow
    Write-Host ""
    Write-Host "4. 同步更新：" -ForegroundColor Cyan
    Write-Host "   python ai-code-ext.py sync" -ForegroundColor Yellow
    Write-Host ""
    Write-Host "5. 查看缓存状态：" -ForegroundColor Cyan
    Write-Host "   python ai-code-ext.py cache status" -ForegroundColor Yellow
    Write-Host ""
    Write-Host "更多信息请查看 .ai\docs\README.md" -ForegroundColor Cyan
}

# 主函数
function Main {
    Write-Host "========================================" -ForegroundColor Cyan
    Write-Host "AI命令安装器 - 自动安装脚本" -ForegroundColor Cyan
    Write-Host "========================================" -ForegroundColor Cyan
    Write-Host ""

    Write-Info "开始安装AI命令..."

    # 切换到安装路径
    Push-Location $InstallPath

    try {
        if (-not (Test-PythonEnvironment)) {
            exit 1
        }

        if (-not (Test-Dependencies)) {
            exit 1
        }

        New-RequiredDirectories

        if (-not (Install-AICommands)) {
            exit 1
        }

        Set-FilePermissions
        New-ConfigurationFile

        if (Test-Installation) {
            Write-Host ""
            Write-Host "========================================" -ForegroundColor Green
            Write-Host "安装成功完成！" -ForegroundColor Green
            Write-Host "========================================" -ForegroundColor Green
            Show-Usage
        } else {
            Write-Host ""
            Write-Host "========================================" -ForegroundColor Red
            Write-Error "安装过程中出现问题，请检查错误信息"
            Write-Host "========================================" -ForegroundColor Red
            exit 1
        }
    } finally {
        Pop-Location
    }
}

# 执行主函数
Main